//******************************************************************************
 //* <PRE>
 //* JS name   : jquery.validationEngine.js
 //* Comment    : nara validate operation
 //*
 //* History    : 1.0
 //*            
 //* </PRE>
 //* DATE       : 2011/05/14
 //* @author    : 
 //* Copyright (C) 2011 by 삼성 SDS All right reserved.
//*****************************************************************************

 var naraValidateCheck=false;     //가장 최근의 validate한 결과값입니다 
 var naraFileValidateCheck=true;  //가장 최근의 file validate한 결과값입니다
 var beforeValidateCheckisError; //isError의 값을 저장합니다 
(function($) 
{
	var beforeValidateId="none";       //oneValidate인경우 현재 validate대상의 바로 앞에 validate를 시도한 object의 id를 가집니다 
	var isLongTimeValidateDiv=false;   //true로 지정되면 바로 닫지않고 5초이상 유지합니다 
	var isOneValidateDiv=false;         //true이면 하나의 validator만 남김
	
	$.fn.validationEngine = function(settings)
	{
		  
	if($.validationEngineLanguage){				
		allRules = $.validationEngineLanguage.allRules;
	}else{
		$.validationEngine.debug("validation을 위한 구현관련 설정이 잘못되었습니다 파일linclude등 기본설정을 확인하세요");
	}
 	settings = jQuery.extend({
		allrules:allRules,
		validationEventTriggers:"focusout",					
		inlineValidation: false,	
		returnIsValid:false,
		liveEvent:true,
		unbindEngine:true,
		containerOverflow:false,
		containerOverflowDOM:"",
		ajaxSubmit: false,
		scroll:true,
		promptPosition: "topRight",	
		success : false,
		beforeSuccess :  function() {},
		failure : function() {}
	}, settings);	
	$.validationEngine.settings = settings;
	$.validationEngine.ajaxValidArray = new Array();	
	
	if(settings.inlineValidation == true)
	{ 	
		
		//
		if(!settings.returnIsValid)
		{	
			
			allowReturnIsvalid = false;
			if(settings.liveEvent){						
				$(this).find("[class*=validate][type!=checkbox]").live(settings.validationEventTriggers, function(caller){ _inlinEvent(this);})
				$(this).find("[class*=validate][type=checkbox]").live("click", function(caller){ _inlinEvent(this); })
			}else{
				$(this).find("[class*=validate]").not("[type=checkbox]").bind(settings.validationEventTriggers, function(caller){ _inlinEvent(this); })
				$(this).find("[class*=validate][type=checkbox]").bind("click", function(caller){ _inlinEvent(this); })
			}
			firstvalid = false;
		}
		
		function _inlinEvent(caller)
		{
			$.validationEngine.settings = settings;
			if($.validationEngine.intercept == false || !$.validationEngine.intercept){		// STOP INLINE VALIDATION THIS TIME ONLY
				$.validationEngine.onSubmitValid=false;			    
				$.validationEngine.loadValidation(caller); 
			}else{
				$.validationEngine.intercept = false;
			}
		}
	}
	
	if (settings.returnIsValid){		
		if ($.validationEngine.submitValidation(this,settings)){
			
			return false;
		}else{
			
			return true;
		}
	}
	
	//call submit을 binding합니다
	$(this).bind("submit", function(caller)
	{   
		isOneValidateDiv = false;
		$.validationEngine.onSubmitValid = true;
		$.validationEngine.settings = settings;
		
		if($.validationEngine.submitValidation(this,settings) == false)  
		{	
			//view에 대한 validation이 성공적으로 완료된 경우
			if($.validationEngine.submitForm(this,settings) == true) return false;
		}
		else  //validation에 위반됨
		{
			JQ_setProcessMsg_delete();
			 
			isOneValidateDiv = false;
			naraValidateCheck = false;
			settings.failure && settings.failure(); 
			$(this).delay(5000,function()
			{
				//alert('c1');
				$.validationEngine.closePrompt(".formError",true)
				isOneValidateDiv = true;
			});
			
			return false;
		}		
		
		
	})
	
	$(".formError").live("click",function(){	
		$(this).fadeOut(150,function(){ 	$(this).remove()	}) 
	})
};	
$.validationEngine = {
	defaultSetting : function(caller) {		//caller object에 대한 기본세팅을 적용합니다
		if($.validationEngineLanguage){				
			allRules = $.validationEngineLanguage.allRules;
		}else{
			$.validationEngine.debug("Validation engine rules are not loaded check your external file");
		}	
		settings = {
			allrules:allRules,
			validationEventTriggers:"blur",					
			inlineValidation: true,	
			containerOverflow:false,
			containerOverflowDOM:"",
			returnIsValid:false,
			scroll:true,
			unbindEngine:true,
			ajaxSubmit: false,
			promptPosition: "topRight",	//validation div box의 위치를 지정합니다: topLeft, topRight, bottomLeft, centerRight, bottomRight
			success : false,
			failure : function() {}
		}	
		$.validationEngine.settings = settings;
	},
	loadValidation : function(caller) {		// GET VALIDATIONS TO BE EXECUTED
		if(!$.validationEngine.settings) $.validationEngine.defaultSetting()
		rulesParsing = $(caller).attr('class');
		rulesRegExp = /\[(.*)\]/;
		getRules = rulesRegExp.exec(rulesParsing);
		if(getRules == null) return false;
		str = getRules[1];
		pattern = /\[|,|\]/;
		result= str.split(pattern);			
		var validateCalll = $.validationEngine.validateCall(caller,result)
		return validateCalll;
	},
	validateCall : function(caller,rules) {	// EXECUTE VALIDATION REQUIRED BY THE USER FOR THIS FIELD
		
		
		var promptText =""	
		
		if(!$(caller).attr("id")) $.validationEngine.debug("This field have no ID attribut( name & class ayed): "+$(caller).attr("name")+" "+$(caller).attr("class"))

		caller = caller;
		ajaxValidate = false;
		var callerName = $(caller).attr("name");
		$.validationEngine.isError = false;
		beforeValidateCheckisError = false;
		$.validationEngine.showTriangle = true;
		callerType = $(caller).attr("type");

		for (i=0; i<rules.length;i++){
			
			switch ( $.trim(rules[i])){
			case "length": 
				 _length(caller,rules,i);
			break;	
			case "optional": 
				if(!$(caller).val()){
					//alert('c2');
					$.validationEngine.closePrompt(caller);
					return $.validationEngine.isError;
				}
			break;
			case "required": 
				_required(caller,rules);
			break;
			case "custom": 
				 _customRegex(caller,rules,i);
			break;
			case "exemptString": 
				 _exemptString(caller,rules,i);
			break;
			case "ajax": 
				if(!$.validationEngine.onSubmitValid) _ajax(caller,rules,i);	
			break;
			case "maxCheckbox": 
				_maxCheckbox(caller,rules,i);
			 	groupname = $(caller).attr("name");
			 	caller = $("input[name='"+groupname+"']");
			break;
			case "minCheckbox": 
				_minCheckbox(caller,rules,i);
				groupname = $(caller).attr("name");
			 	caller = $("input[name='"+groupname+"']");
			break;
			case "confirm": 
				 _confirm(caller,rules,i);
			break;
			case "funcCall": 
		     	_funcCall(caller,rules,i);
			break;
			default :;
			};
		};
		radioHack();
		if ($.validationEngine.isError == true){
			var linkTofieldText = "." +$.validationEngine.linkTofield(caller);
			if(linkTofieldText != "."){
				if(!$(linkTofieldText)[0]){
					//alert('b1');
					$.validationEngine.buildPrompt(caller,promptText,"error")
				}else{	
					$.validationEngine.updatePromptText(caller,promptText);
				}	
			}else{
				$.validationEngine.updatePromptText(caller,promptText);
			}
		}else{
			
			if (isLongTimeValidateDiv == true)
			{
				
				/*
				$(this).delay(5000,function()
				{
					//alert('c3');
					$.validationEngine.closePrompt(caller);
				});
				*/
			}
			else
			{
				//alert('c4');
				$.validationEngine.closePrompt(caller);	
			}
			isLongTimeValidateDiv = false;
		}			
		/* UNFORTUNATE RADIO AND CHECKBOX GROUP HACKS */
		/* As my validation is looping input with id's we need a hack for my validation to understand to group these inputs */
		function radioHack(){
	      if($("input[name='"+callerName+"']").size()> 1 && (callerType == "radio" || callerType == "checkbox")) {        // Hack for radio/checkbox group button, the validation go the first radio/checkbox of the group
	          caller = $("input[name='"+callerName+"'][type!=hidden]:first");     
	          $.validationEngine.showTriangle = false;
	      }      
	    }
		
		
		function _required(caller,rules){   
			
			
			callerType = $(caller).attr("type");
			if (callerType == "text" || callerType == "password" || callerType == "textarea"){
								
				if(! $.trim( $(caller).val() ) ){
					
					$.validationEngine.isError = true;
					
					beforeValidateCheckisError = true;
					promptText += $.validationEngine.settings.allrules[rules[i]].alertText+"<br />";
				}	
			}	
			if (callerType == "radio" || callerType == "checkbox" ){
				callerName = $(caller).attr("name");
		
				if($("input[name='"+callerName+"']:checked").size() == 0) {
					$.validationEngine.isError = true;
					beforeValidateCheckisError = true;
					if($("input[name='"+callerName+"']").size() ==1) {
						promptText += $.validationEngine.settings.allrules[rules[i]].alertTextCheckboxe+"<br />"; 
					}else{
						 promptText += $.validationEngine.settings.allrules[rules[i]].alertTextCheckboxMultiple+"<br />";
					}	
				}
			}	
			if (callerType == "select-one") {		
				if(!$(caller).val()) {
					$.validationEngine.isError = true;
					beforeValidateCheckisError = true;
					promptText += $.validationEngine.settings.allrules[rules[i]].alertText+"<br />";
				}
			}
			if (callerType == "select-multiple") { 	
				if(!$(caller).find("option:selected").val()) {
					$.validationEngine.isError = true;
					beforeValidateCheckisError = true;
					promptText += $.validationEngine.settings.allrules[rules[i]].alertText+"<br />";
				}
			}
			
			
		}
		function _customRegex(caller,rules,position){		 // VALIDATE REGEX RULES
			customRule = rules[position+1];
		
			pattern = eval($.validationEngine.settings.allrules[customRule].regex);
			
			if(!pattern.test($(caller).attr('value'))){
				$.validationEngine.isError = true;
				beforeValidateCheckisError = true;
				promptText += $.validationEngine.settings.allrules[customRule].alertText+"<br />";
			}
		}
		function _exemptString(caller,rules,position){		 // VALIDATE REGEX RULES
			customString = rules[position+1];
			if(customString == $(caller).attr('value')){
				$.validationEngine.isError = true;
				beforeValidateCheckisError = true;
				promptText += $.validationEngine.settings.allrules['required'].alertText+"<br />";
			}
		}
		
		function _funcCall(caller,rules,position){  		// VALIDATE CUSTOM FUNCTIONS OUTSIDE OF THE ENGINE SCOPE
			
			var funcname = rules[position+1];		    
		    var fn = window[funcname];
		    
			if (typeof(fn) === 'function'){
				var fn_result = fn();
				if(fn_result != ""){
					$.validationEngine.isError = true;
					beforeValidateCheckisError = true;
					promptText += fn_result +"<br />";
				}
			}
		}
		function _ajax(caller,rules,position){				 // VALIDATE AJAX RULES
			
			customAjaxRule = rules[position+1];
			postfile = $.validationEngine.settings.allrules[customAjaxRule].file;
			fieldValue = $(caller).val();
			ajaxCaller = caller;
			fieldId = $(caller).attr("id");
			ajaxValidate = true;
			ajaxisError = $.validationEngine.isError;
			
			if($.validationEngine.settings.allrules[customAjaxRule].extraData){
				extraData = $.validationEngine.settings.allrules[customAjaxRule].extraData;
			}else{
				extraData = "";
			}
			/* AJAX VALIDATION HAS ITS OWN UPDATE AND BUILD UNLIKE OTHER RULES */	
			if(!ajaxisError){
				$.ajax({
				   	type: "POST",
				   	url: postfile,
				   	async: true,
				   	data: "validateValue="+fieldValue+"&validateId="+fieldId+"&validateError="+customAjaxRule+"&extraData="+extraData,
				   	beforeSend: function(){		// BUILD A LOADING PROMPT IF LOAD TEXT EXIST		   			
				   		if($.validationEngine.settings.allrules[customAjaxRule].alertTextLoad){
				   		
				   			if(!$("div."+fieldId+"formError")[0]){
								//alert('b2');				   				
	 			 				return $.validationEngine.buildPrompt(ajaxCaller,$.validationEngine.settings.allrules[customAjaxRule].alertTextLoad,"load");
	 			 			}else{
	 			 				$.validationEngine.updatePromptText(ajaxCaller,$.validationEngine.settings.allrules[customAjaxRule].alertTextLoad,"load");
	 			 			}
			   			}
			  	 	},
			  	 	error: function(data,transport){ $.validationEngine.debug("error in the ajax: "+data.status+" "+transport) },
					success: function(data){					// GET SUCCESS DATA RETURN JSON
						data = eval( "("+data+")");				// GET JSON DATA FROM PHP AND PARSE IT
						ajaxisError = data.jsonValidateReturn[2];
						customAjaxRule = data.jsonValidateReturn[1];
						ajaxCaller = $("#"+data.jsonValidateReturn[0])[0];
						fieldId = ajaxCaller;
						ajaxErrorLength = $.validationEngine.ajaxValidArray.length;
						existInarray = false;
						
			 			 if(ajaxisError == "false"){			// DATA FALSE UPDATE PROMPT WITH ERROR;
			 			 	
			 			 	_checkInArray(false)				// Check if ajax validation alreay used on this field
			 			 	
			 			 	if(!existInarray){		 			// Add ajax error to stop submit		 		
				 			 	$.validationEngine.ajaxValidArray[ajaxErrorLength] =  new Array(2);
				 			 	$.validationEngine.ajaxValidArray[ajaxErrorLength][0] = fieldId;
				 			 	$.validationEngine.ajaxValidArray[ajaxErrorLength][1] = false;
				 			 	existInarray = false;
			 			 	}
				
			 			 	$.validationEngine.ajaxValid = false;
							promptText += $.validationEngine.settings.allrules[customAjaxRule].alertText+"<br />";
							$.validationEngine.updatePromptText(ajaxCaller,promptText,"",true);				
						 }else{	 
						 	_checkInArray(true);
						 	$.validationEngine.ajaxValid = true; 			
						 	if(!customAjaxRule)	{$.validationEngine.debug("wrong ajax response, are you on a server or in xampp? if not delete de ajax[ajaxUser] validating rule from your form ")}		   
						 	if($.validationEngine.settings.allrules[customAjaxRule].alertTextOk){	// NO OK TEXT MEAN CLOSE PROMPT	 			
	 			 				 				$.validationEngine.updatePromptText(ajaxCaller,$.validationEngine.settings.allrules[customAjaxRule].alertTextOk,"pass",true);
 			 				}else{
				 			 	ajaxValidate = false;		 	
								//alert('c5');
				 			 	$.validationEngine.closePrompt(ajaxCaller);
 			 				}		
			 			 }
			 			function  _checkInArray(validate){
			 				for(x=0;x<ajaxErrorLength;x++){
			 			 		if($.validationEngine.ajaxValidArray[x][0] == fieldId){
			 			 			$.validationEngine.ajaxValidArray[x][1] = validate;
			 			 			existInarray = true;
			 			 		
			 			 		}
			 			 	}
			 			}
			 		}				
				});
			}
		}
		function _confirm(caller,rules,position){		 // VALIDATE FIELD MATCH
			confirmField = rules[position+1];
		    
			if($(caller).attr('value') != $("#"+confirmField).attr('value')){
				$.validationEngine.isError = true;
				beforeValidateCheckisError = true;
				promptText += $.validationEngine.settings.allrules["confirm"].alertText+"<br />";
			}
		}
		
		function _length_chk(obj_name,max_length,currLength) 
		{
			
			var ls_str     = $("#"+obj_name).attr('value'); // 이벤트가 일어난 컨트롤의 value 값
		    //var li_str_len = ls_str.length;  // 전체길이
		    // 변수초기화
		    var li_max      = max_length; // 제한할 글자수 크기
		    var i           = 0;  // for문에 사용
		    var li_byte     = 0;  // 한글일경우는 2 그밗에는 1을 더함
		    var li_len      = 0;  // substring하기 위해서 사용
		    var ls_one_char = ""; // 한글자씩 검사한다
		    var ls_str2     = ""; // 글자수를 초과하면 제한할수 글자전까지만 보여준다.
		    
			//alert(ls_str);
		    for(i=0; i< currLength; i++)
		    {
		       // 한글자추출
		       ls_one_char = ls_str.charCodeAt(i);
		       
		       // 한글이면 2를 더한다.
		       if (ls_one_char > 255)
		       {
		          li_byte = li_byte+2;
		       }
		       // 그외의 경우는 1을 더한다.
		       else
		       {
		          li_byte++;
		       }
		       // 전체 크기가 li_max를 넘지않으면
		       if(li_byte <= li_max)
		       {
		          li_len = i + 1;
		       }
		    }   
		    
		    // 전체길이를 초과하면
		    if(li_byte > li_max)
		    {
		       //alert( li_max + " Bytes를 초과 입력할수 없습니다. \n 초과된 내용은 자동으로 삭제 됩니다. ");
		       ls_str2 = ls_str.substr(0, li_len);
		       obj_name.value = ls_str2; 
		      
		    }
		       
			return li_byte;
		    
		}
		
		function _length(caller,rules,position){    	  // VALIDATE LENGTH
		
			startLength = eval(rules[position+1]);
			endLength = eval(rules[position+2]);
			feildLength = $(caller).attr('value').length;
			var tmpCurrSize = 0; 
			var targetObj = caller.id;
			
			//alert('_length:'+startLength+":"+endLength+":"+feildLength);
			
			tmpCurrSize = _length_chk(targetObj,endLength,feildLength);
			
		    
			//view object에 대한 입력길이를 실시간으로 체크합니다 
			if(feildLength<startLength || feildLength>endLength || tmpCurrSize > endLength)
			{
				//////////////////
				//CANCELED!!!!!!!!
				//////////////////
				
				//입력길이를 초과한경우. validation rule를 벋어나므로 submit이 cancel됨
				$.validationEngine.isError = true; // true로 설정되어 submit이 cancel됨
				beforeValidateCheckisError = true;
				
				
				promptText += $.validationEngine.settings.allrules["length"].alertText+startLength+$.validationEngine.settings.allrules["length"].alertText2+endLength+$.validationEngine.settings.allrules["length"].alertText3+"<br />"
				if (tmpCurrSize > endLength){promptText = promptText + "입력범위를 초과하였습니다<br /> "};
				
				isLongTimeValidateDiv = true;
			}
			else
			{
				isLongTimeValidateDiv = false;

			/**	 실시간으로 정상인것도 보여주는 것을 막음 
				//////////////////
				//SUCCESS!!!!!!!!!
				//////////////////
				
				//유저편의를 위해 validate div가 하나인경우와 해당 object가 true인 경우만 실시간 체킹 메세지를 보여줌 
				//if start
				if (isOneValidateDiv == true) 
				{
					if (($(caller).attr('disabled') == true) || ($(caller).attr('readonly') == true)) 
					{
					}
					else
					{	
						promptText += "현재 [" + tmpCurrSize + "]단어 입력됨 " + startLength +
						$.validationEngine.settings.allrules["length"].alertText2 + endLength +
						$.validationEngine.settings.allrules["length"].alertText3 +
						"<br/>"
						
						var linkTofieldText = "." + $.validationEngine.linkTofield(caller);

						if (linkTofieldText != ".") {
							if (!$(linkTofieldText)[0]) {
								
								//alert('b3');
								isLongTimeValidateDiv = true;
								//신규 메세지 생성
								
								//입력길이가 인정되는시점, 이 시점에 submit은 정상적으로 수행됨 
								$.validationEngine.isError = false; //false로 설정되어 submit이 수행됨 
								$.validationEngine.buildPrompt(caller, promptText, "error");
								
								
							}
							else {
								
								isLongTimeValidateDiv = true;
								//아직 메세지 div가 남아잇음, text만 변경해줌
								
								//입력길이가 인정되는시점, 이 시점에 submit은 정상적으로 수행됨 
								$.validationEngine.isError = false; //false로 설정되어 submit이 수행됨
								$.validationEngine.updatePromptText(caller, promptText);
								
								
							}
						}
						else {
							//alert('updatep2');
							isLongTimeValidateDiv = true;
							//아직 메세지 div가 남아잇음, text만 변경해줌
							
							//입력길이가 인정되는시점, 이 시점에 submit은 정상적으로 수행됨 
							$.validationEngine.isError = false; //false로 설정되어 submit이 수행됨
							$.validationEngine.updatePromptText(caller, promptText);
							
							
						}
					}
				}
				//end if
			    **/
			}
		}
		
		function _length_chk2(obj_name,min_length,currLength) 
		{
			
			var ls_str     = $("#"+obj_name).attr('value'); // 이벤트가 일어난 컨트롤의 value 값
		    //var li_str_len = ls_str.length;  // 전체길이
		    // 변수초기화
		    var li_min      = min_length; // 제한할 글자수 크기
		    var i           = 0;  // for문에 사용
		    var li_byte     = 0;  // 한글일경우는 2 그밗에는 1을 더함
		    var li_len      = 0;  // substring하기 위해서 사용
		    var ls_one_char = ""; // 한글자씩 검사한다
		    
			//alert(ls_str);
		    for(i=0; i< currLength; i++)
		    {
		       // 한글자추출
		       ls_one_char = ls_str.charCodeAt(i);
		       
		       // 한글이면 2를 더한다.
		       if (ls_one_char > 255)
		       {
		          li_byte = li_byte+2;
		       }
		       // 그외의 경우는 1을 더한다.
		       else if(ls_one_char == 42)
		       {
		    	   
		       }
		       else 
		       {
		          li_byte++;
		       }
		       // 전체 크기가 li_min을 넘으면
		       if(li_byte >= li_min)
		       {
		          li_len = i + 1;
		       }
		    }   
		       
			return li_byte;
		    
		}
		
		function _length2(caller,rules,position){    	  // VALIDATE LENGTH
			
			startLength = eval(rules[position+1]);
			//endLength = eval(rules[position+2]);
			fieldLength = $(caller).attr('value').length;
			var tmpCurrSize = 0; 
			var targetObj = caller.id;
			
			tmpCurrSize = _length_chk2(targetObj,startLength,fieldLength);
			
			//view object에 대한 입력길이를 실시간으로 체크합니다 
			if(fieldLength<startLength || tmpCurrSize < startLength)
			{
				//////////////////
				//CANCELED!!!!!!!!
				//////////////////
				
				//입력길이를 초과한경우. validation rule를 벋어나므로 submit이 cancel됨
				$.validationEngine.isError = true; // true로 설정되어 submit이 cancel됨
				beforeValidateCheckisError = true;
				
				promptText += $.validationEngine.settings.allrules["length2"].alertText+startLength+$.validationEngine.settings.allrules["length2"].alertText2+"<br />"
				if (tmpCurrSize < startLength){promptText = promptText + "최소입력범위보다 작습니다<br /> "};
				
				isLongTimeValidateDiv = true;
			}
			else
			{
				isLongTimeValidateDiv = false;
			}
		}
		
		function _maxCheckbox(caller,rules,position){  	  // VALIDATE CHECKBOX NUMBER
		
			nbCheck = eval(rules[position+1]);
			groupname = $(caller).attr("name");
			groupSize = $("input[name='"+groupname+"']:checked").size();
			if(groupSize > nbCheck){	
				$.validationEngine.showTriangle = false;
				$.validationEngine.isError = true;
				beforeValidateCheckisError = true;
				promptText += $.validationEngine.settings.allrules["maxCheckbox"].alertText+"<br />";
			}
		}
		function _minCheckbox(caller,rules,position){  	  // VALIDATE CHECKBOX NUMBER
		
			nbCheck = eval(rules[position+1]);
			groupname = $(caller).attr("name");
			groupSize = $("input[name='"+groupname+"']:checked").size();
			
			if(groupSize < nbCheck){	
			
				$.validationEngine.isError = true;
				beforeValidateCheckisError = true;
				$.validationEngine.showTriangle = false;
				promptText += $.validationEngine.settings.allrules["minCheckbox"].alertText+" "+nbCheck+" "+$.validationEngine.settings.allrules["minCheckbox"].alertText2+"<br />";
			}
		}
		return ($.validationEngine.isError) ? $.validationEngine.isError : false;
	},
	submitForm : function(caller){
		if($.validationEngine.settings.ajaxSubmit){		
			if($.validationEngine.settings.ajaxSubmitExtraData){
				extraData = $.validationEngine.settings.ajaxSubmitExtraData;
			}else{
				extraData = "";
			}
			$.ajax({
			   	type: "POST",
			   	url: $.validationEngine.settings.ajaxSubmitFile,
			   	async: true,
			   	data: $(caller).serialize()+"&"+extraData,
			   	error: function(data,transport){ $.validationEngine.debug("error in the ajax: "+data.status+" "+transport) },
			   	success: function(data){
			   		if(data == "true"){			// EVERYTING IS FINE, SHOW SUCCESS MESSAGE
			   			$(caller).css("opacity",1)
			   			$(caller).animate({opacity: 0, height: 0}, function(){
			   				$(caller).css("ay","none");
			   				$(caller).before("<div class='ajaxSubmit'>"+$.validationEngine.settings.ajaxSubmitMessage+"</div>");
							//alert('c6');
			   				$.validationEngine.closePrompt(".formError",true); 	
			   				$(".ajaxSubmit").show("slow");
			   				if ($.validationEngine.settings.success){	// AJAX SUCCESS, STOP THE LOCATION UPDATE
								$.validationEngine.settings.success && $.validationEngine.settings.success(); 
								return false;
							}
			   			})
		   			}else{						// HOUSTON WE GOT A PROBLEM (SOMETING IS NOT VALIDATING)
			   			data = eval( "("+data+")");	
			   			if(!data.jsonValidateReturn){
			   				 $.validationEngine.debug("you are not going into the success fonction and jsonValidateReturn return nothing");
			   			}
			   			errorNumber = data.jsonValidateReturn.length	
			   			for(index=0; index<errorNumber; index++){	
			   				fieldId = data.jsonValidateReturn[index][0];
			   				promptError = data.jsonValidateReturn[index][1];
			   				type = data.jsonValidateReturn[index][2];
							//alert('b4');
			   				$.validationEngine.buildPrompt(fieldId,promptError,type);
		   				}
	   				}
   				}
			})	
			return true;
		}
		// LOOK FOR BEFORE SUCCESS METHOD		
			if(!$.validationEngine.settings.beforeSuccess()){
				if ($.validationEngine.settings.success){	// AJAX SUCCESS, STOP THE LOCATION UPDATE
					if($.validationEngine.settings.unbindEngine){ $(caller).unbind("submit") }
					$.validationEngine.settings.success && $.validationEngine.settings.success(); 
					return true;
				}
			}else{
				return true;
			} 
		return false;
	},
	
	
	buildPrompt : function(caller,promptText,type,ajaxed) {			
		
		if (isOneValidateDiv == true) 
		{
			if (beforeValidateId != 'none') {
				if (beforeValidateId != caller.id) {
					//alert('cc');
					$.validationEngine.closePrompt($("#" + beforeValidateId));
				}
			}
		}
		
		beforeValidateId = caller.id;
		
		if(!$.validationEngine.settings){
			$.validationEngine.defaultSetting()
		}
		deleteItself = "." + $(caller).attr("id") + "formError"
	
		if($(deleteItself)[0]){
			
			$(deleteItself).stop();
			$(deleteItself).remove();
		}
		var divFormError = document.createElement('div');
		var formErrorContent = document.createElement('div');
		linkTofield = $.validationEngine.linkTofield(caller)
		$(divFormError).addClass("formError")
		
		if(type == "pass") $(divFormError).addClass("greenPopup")
		if(type == "load") $(divFormError).addClass("blackPopup")
		if(ajaxed) $(divFormError).addClass("ajaxed")
		
		$(divFormError).addClass(linkTofield);
		//alert(linkTofield);
		$(formErrorContent).addClass("formErrorContent");
		
		if($.validationEngine.settings.containerOverflow){		// Is the form contained in an overflown container?
			$(caller).before(divFormError);
		}else{
			$("body").append(divFormError);
		}
		
		$(divFormError).append(formErrorContent);
			
		if($.validationEngine.showTriangle != false){		// NO TRIANGLE ON MAX CHECKBOX AND RADIO
			var arrow = document.createElement('div');
			$(arrow).addClass("formErrorArrow");
			$(divFormError).append(arrow);
			if($.validationEngine.settings.promptPosition == "bottomLeft" || $.validationEngine.settings.promptPosition == "bottomRight"){
			$(arrow).addClass("formErrorArrowBottom")
			$(arrow).html('<div class="line1"><!-- --></div><div class="line2"><!-- --></div><div class="line3"><!-- --></div><div class="line4"><!-- --></div><div class="line5"><!-- --></div><div class="line6"><!-- --></div><div class="line7"><!-- --></div><div class="line8"><!-- --></div><div class="line9"><!-- --></div><div class="line10"><!-- --></div>');
		}
			if($.validationEngine.settings.promptPosition == "topLeft" || $.validationEngine.settings.promptPosition == "topRight"){
				$(divFormError).append(arrow);
				$(arrow).html('<div class="line10"><!-- --></div><div class="line9"><!-- --></div><div class="line8"><!-- --></div><div class="line7"><!-- --></div><div class="line6"><!-- --></div><div class="line5"><!-- --></div><div class="line4"><!-- --></div><div class="line3"><!-- --></div><div class="line2"><!-- --></div><div class="line1"><!-- --></div>');
			}
		}
		
		$(formErrorContent).html(promptText)
		
		var calculatedPosition = $.validationEngine.calculatePosition(caller,promptText,type,ajaxed,divFormError)
		
		calculatedPosition.callerTopPosition +="px";
		calculatedPosition.callerleftPosition +="px";
		calculatedPosition.marginTopSize +="px"
		$(divFormError).css({
			"top":calculatedPosition.callerTopPosition,
			"left":calculatedPosition.callerleftPosition,
			"marginTop":calculatedPosition.marginTopSize,
			"opacity":0,
			"position":"absolute",
			"z-index":900
		})
		
		
		
		
		return $(divFormError).animate({"opacity":0.87},function(){return true;});	
	},
	updatePromptText : function(caller,promptText,type,ajaxed) {	// UPDATE TEXT ERROR IF AN ERROR IS ALREADY AYED
		
		linkTofield = $.validationEngine.linkTofield(caller);
		var updateThisPrompt =  "."+linkTofield;
		
		if(type == "pass") { $(updateThisPrompt).addClass("greenPopup") }else{ $(updateThisPrompt).removeClass("greenPopup")};
		if(type == "load") { $(updateThisPrompt).addClass("blackPopup") }else{ $(updateThisPrompt).removeClass("blackPopup")};
		if(ajaxed) { $(updateThisPrompt).addClass("ajaxed") }else{ $(updateThisPrompt).removeClass("ajaxed")};
	
		$(updateThisPrompt).find(".formErrorContent").html(promptText);
		
		var calculatedPosition = $.validationEngine.calculatePosition(caller,promptText,type,ajaxed,updateThisPrompt)
		
		calculatedPosition.callerTopPosition +="px";
		calculatedPosition.callerleftPosition +="px";
		calculatedPosition.marginTopSize +="px"
		$(updateThisPrompt).animate({ "top":calculatedPosition.callerTopPosition,"marginTop":calculatedPosition.marginTopSize });
	},
	calculatePosition : function(caller,promptText,type,ajaxed,divFormError){
		
		if($.validationEngine.settings.containerOverflow){		// Is the form contained in an overflown container?
			callerTopPosition = 0;
			callerleftPosition = 0;
			callerWidth =  $(caller).width();
			inputHeight = $(divFormError).height();					// compasation for the triangle
			var marginTopSize = "-"+inputHeight;
		}else{
			callerTopPosition = $(caller).offset().top;
			callerleftPosition = $(caller).offset().left;
			callerWidth =  $(caller).width();
			inputHeight = $(divFormError).height();
			var marginTopSize = 0;
		}
		
		/* POSITIONNING */
		if($.validationEngine.settings.promptPosition == "topRight"){ 
			if($.validationEngine.settings.containerOverflow){		// Is the form contained in an overflown container?
				callerleftPosition += callerWidth -30;
			}else{
				callerleftPosition +=  callerWidth -30; 
				callerTopPosition += -inputHeight; 
			}
		}
		if($.validationEngine.settings.promptPosition == "topLeft"){ callerTopPosition += -inputHeight -10; }
		
		if($.validationEngine.settings.promptPosition == "centerRight"){ callerleftPosition +=  callerWidth +13; }
		
		if($.validationEngine.settings.promptPosition == "bottomLeft"){
			callerHeight =  $(caller).height();
			callerTopPosition = callerTopPosition + callerHeight + 15;
		}
		if($.validationEngine.settings.promptPosition == "bottomRight"){
			callerHeight =  $(caller).height();
			callerleftPosition +=  callerWidth -30;
			callerTopPosition +=  callerHeight +5;
		}
		return {
			"callerTopPosition":callerTopPosition,
			"callerleftPosition":callerleftPosition,
			"marginTopSize":marginTopSize
		}
	},
	linkTofield : function(caller){
		var linkTofield = $(caller).attr("id") + "formError";
		linkTofield = linkTofield.replace(/\[/g,""); 
		linkTofield = linkTofield.replace(/\]/g,"");
		return linkTofield;
	},
	closePrompt : function(caller,outside) {						// CLOSE PROMPT WHEN ERROR CORRECTED
		if(!$.validationEngine.settings){
			$.validationEngine.defaultSetting()
		}
		if(outside){
			$(caller).fadeTo("fast",0,function(){				
				$(caller).remove();
			});
			return false;
		}
		if(typeof(ajaxValidate)=='undefined'){ajaxValidate = false}
		if(!ajaxValidate){
			linkTofield = $.validationEngine.linkTofield(caller);
			closingPrompt = "."+linkTofield;
			$(closingPrompt).fadeTo("fast",0,function(){				
				$(closingPrompt).remove();
			});
		}
	},
	debug : function(error) {
		if(!$("#debugMode")[0]){
			$("body").append("<div id='debugMode'><div class='debugError'><strong>This is a debug mode, you got a problem with your form, it will try to help you, refresh when you think you nailed down the problem</strong></div></div>");
		}
		$(".debugError").append("<div class='debugerror'>"+error+"</div>");
	},			
	submitValidation : function(caller) {					// FORM SUBMIT VALIDATION LOOPING INLINE VALIDATION
		var stopForm = false;
		$.validationEngine.ajaxValid = true;
		var toValidateSize = $(caller).find("[class*=validate]").size();
		
		//JQ_SetFileChk();
		$(caller).find("[class*=validate]").each(function()
		{
			linkTofield = $.validationEngine.linkTofield(this);
			
			if(!$("."+linkTofield).hasClass("ajaxed")){	// DO NOT UPDATE ALREADY AJAXED FIELDS (only happen if no normal errors, don't worry)
					
				var validationPass = $.validationEngine.loadValidation(this);
				return(validationPass) ? stopForm = true : "";					
			};
		});
		
		ajaxErrorLength = $.validationEngine.ajaxValidArray.length;		// LOOK IF SOME AJAX IS NOT VALIDATE
		for(x=0;x<ajaxErrorLength;x++)
		{
	 		if($.validationEngine.ajaxValidArray[x][1] == false) $.validationEngine.ajaxValid = false;
 		}
		
		if(stopForm || !$.validationEngine.ajaxValid)
		{		// GET IF THERE IS AN ERROR OR NOT FROM THIS VALIDATION FUNCTIONS
			if($.validationEngine.settings.scroll){
				if(!$.validationEngine.settings.containerOverflow){
					var destination = $(".formError:not('.greenPopup'):first").offset().top;
					$(".formError:not('.greenPopup')").each(function(){
						testDestination = $(this).offset().top;
						if(destination>testDestination) destination = $(this).offset().top;
					})
					$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, 1100);
				}else{
					var destination = $(".formError:not('.greenPopup'):first").offset().top;
					var scrollContainerScroll = $($.validationEngine.settings.containerOverflowDOM).scrollTop();
					var scrollContainerPos = - parseInt($($.validationEngine.settings.containerOverflowDOM).offset().top);
					var destination = scrollContainerScroll + destination + scrollContainerPos -5
					var scrollContainer = $.validationEngine.settings.containerOverflowDOM+":not(:animated)"
					
					$(scrollContainer).animate({ scrollTop: destination}, 1100);
				}
			}
			return true; //validation에 catch됨, validation 실패, submit을 중단합니다 
		}
		else
		{
			//파일validation의 결과값을 체크함
			
			if (naraFileValidateCheck == true)
			{	
				return false; //validation 성공. submit을 진행함
			}
			else
			{
				return true; //validation 성공. submit을 진행함
			}
			
		}
	}
}
})(jQuery);